<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2024/4/23
 * Time: 15:19
 */

namespace app\logic\index\withdraw;


use app\common\lib\Common;
use app\common\lib\YunZhangHu2;
use app\exception\IndexException;
use app\logic\BaseLogic;
use app\model\user\UserIncomeFlowModel;
use app\model\withdraw\UserWithdrawAccountModel;
use app\model\withdraw\UserWithdrawModel;
use support\Cache;
use support\Db;

class WithdrawLogic extends BaseLogic
{
    protected $model;

    protected static $instance;

    public function __construct()
    {
        parent::__construct();
        $this->model = \app\model\withdraw\UserWithdrawAccountModel::getInstance();
    }

    public static function getInstance()
    {
//        if(is_object(self::$instance)){
//            return self::$instance;
//        }

        return  new self();
    }

    public function bindWithdrawAccount($param)
    {
        if(Common::checkMobile($param['mobile'])==false){
            throw new IndexException(4020,'手机号码错误');
        }

        $cache = Cache::get('sms_auth_code_withdraw_'.$param['mobile']);
        if((!$cache || $param['authcode']!=$cache['code'])){
            throw new IndexException(4020,'验证码错误');
        }

        //云账户用户签约
        try{
            $result = YunZhangHu2::getInstance()->getUserSignStatus([
                'truename'=>$param['truename'],
                'idcard'=>strtoupper($param['idcard']),
            ]);
            if($result['status']==1){
                $param['is_sign'] = 1;
            }else{
                $result = YunZhangHu2::getInstance()->userSign([
                    'truename'=>$param['truename'],
                    'idcard'=>$param['idcard'],
                ]);
                if($result['status']=='ok'){
                    $param['is_sign'] = 1;
                }
            }
        }catch (\Exception $e){
            throw new IndexException(4020,'用户签约失败,请输入正确的姓名和身份证');
        }

        $param['user_sn'] = request()->curUserId;
        $param['is_bind'] = 1;
        $param['type'] = 1;
        $result = $this->model->saveData($param);

        return $result;
    }

    public function getDetail($param)
    {
        try{
            $first = $this->model->getDetail(['user_sn'=>request()->curUserId,'isdel'=>0,'type'=>1],['mobile','truename','account','idcard','is_bind']);
            return $first;
        }catch (IndexException $e){
            return [];
        }
    }

    public function submitWithdraw($param)
    {
        $lock = Common::setnx('submit_withdraw_'.request()->curUserId);
        if($lock==false){
            throw new IndexException(4020,'请勿重复提交');
        }

        $first = $this->model->getWhere(['user_sn'=>request()->curUserId,'isdel'=>0,'type'=>1])->first(['mobile','truename','account','idcard']);
        if($first==false){
            throw new IndexException(4020,'请先绑定转账账号');
        }

        //查看可提现金额
        $canMoney = UserIncomeFlowModel::getInstance()->getWhere(['user_sn'=>request()->curUserId,['status','in',[1,2]]])->sum('amount');
        if($canMoney<$param['withdraw_amount']){
            throw new IndexException(4020,'可提现金额不足'.$param['withdraw_amount'].'元');
        }

        //查看已结算金额
        $settleAmount = UserIncomeFlowModel::getInstance()->getWhere(['user_sn'=>request()->curUserId,'type'=>1,['status','in',[1,2]]])->sum('amount');

        //查看已提现金额
        $withdrawAmount = UserWithdrawModel::getInstance()->getWhere(['user_sn'=>request()->curUserId,['status','in',[0,1,3,5]]])->sum('amount');

        try{
            Db::connection('mysql')->beginTransaction();
            $insert = [
                'user_sn'=>request()->curUserId,
                'amount'=>(float)$param['withdraw_amount'],
                'readly_amount'=>(float)$param['withdraw_amount'],
                'can_money'=>(float)$canMoney,
                'mobile'=>$first['mobile'],
                'truename'=>$first['truename'],
                'account'=>$first['account'],
                'idcard'=>$first['idcard'],
                'type'=>1,
                'total_settle_amount'=>$settleAmount,
                'total_withdraw_amount'=>round($withdrawAmount,2),
            ];
            $id = UserWithdrawModel::getInstance()->saveData($insert);

            $insertFlow = [
                'user_sn'=>request()->curUserId,
                'amount'=>-((float) $param['withdraw_amount']),
                'type'=>2,
                'source_table'=>UserWithdrawModel::getInstance()->getTable(),
                'sourceid'=>$id,
                'status'=>1,
            ];
            UserIncomeFlowModel::getInstance()->insert($insertFlow);
            Db::connection('mysql')->commit();

            return $id;
        }catch (IndexException $e){
            Db::connection('mysql')->rollBack();
            throw $e;
        }catch (\Exception $e){
            Db::connection('mysql')->rollBack();
            throw $e;
        }catch (\Throwable $e){
            Db::connection('mysql')->rollBack();
            throw $e;
        }
    }

    public function getWithdrawList()
    {
        $where = ['user_sn'=>request()->curUserId,'type'=>1];
        $fields = ['user_sn','amount','status','created_at'];
        $order = ['created_at','desc'];
        $data = UserWithdrawModel::getInstance()->index($where,$fields,$order);
        $statusMap = [
            '0'=>'打款中',
            '1'=>'打款中',
            '5'=>'打款中',
            '2'=>'提现失败',
            '3'=>'已提现',
            '4'=>'提现失败',
        ];
        foreach($data['data'] as $val){
            $val['created_at'] = date('Y-m-d',strtotime($val['created_at']));
            $val['createtime'] = date('Y-m-d',strtotime($val['created_at']));
            $val['status_text'] = isset($statusMap[$val['status']])?$statusMap[$val['status']]:'';
        }

        return $data;
    }
}